package so.wy.servicecenter.businessbed.service.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import so.wy.servicecenter.base.exception.ManagerException;
import so.wy.servicecenter.base.exception.ServiceException;
import so.wy.servicecenter.base.frame.baseopt.BaseOptService;
import so.wy.servicecenter.base.frame.dao.PageData;
import so.wy.servicecenter.businessbed.dao.rdb.order.order.OrderDAO;
import so.wy.servicecenter.businessbed.dao.rdb.order.order.OrderDO;
import so.wy.servicecenter.businessbed.dao.rdb.rent_user.RentUserDO;
import so.wy.servicecenter.businessbed.manager.inner.RentUserIManager;
import so.wy.servicecenter.businessbed.service.order.dto.OrderDTO;

import java.util.List;

@Service
@Scope("prototype")
public class OrderService extends BaseOptService<OrderDAO, OrderDO, OrderDTO> {

    @Autowired
    private RentUserIManager rentUserIManager;

    @Override
    protected OrderDTO convert2DTO(OrderDO orderDO) {
        return new OrderDTO(orderDO);
    }

    @Override
    protected OrderDO convert2DO(OrderDTO orderQuery) {
        return orderQuery.convert2DO();
    }

    @Override
    public PageData selectRecordsWithPageByToken(OrderDTO recordQuery, Integer curPage, Integer pageSize, Long userId) throws ServiceException {
        LambdaQueryWrapper<OrderDO> queryWrapper = new LambdaQueryWrapper<>(this.convert2DO(recordQuery));
        if (recordQuery.getStartTime() != null && recordQuery.getEndTime() != null) {
            queryWrapper.ge(OrderDO::getOrderTime, recordQuery.getStartTime()).le(OrderDO::getOrderTime, recordQuery.getEndTime());
        }
        queryWrapper.orderByDesc(OrderDO::getOrderTime);
        PageHelper.startPage(curPage,pageSize);
        return this.pageDtos(list(queryWrapper), this::convert2DTO);
    }

    //获取个人订单信息
    public PageData<OrderDO, OrderDTO> getRentUserOrders(Long userId, Integer curPage, Integer pageSize) throws ServiceException {
        try {
            RentUserDO rentUserDO = rentUserIManager.checkRentUserExist(userId);

            PageHelper.startPage(curPage, pageSize);
            List<OrderDO> list = list(lambdaQuery().eq(OrderDO::getRentUserId, rentUserDO.getRentUserId())
                    .orderByDesc(OrderDO::getOrderTime));

            return pageDtos(list, OrderDTO::new);
        } catch (ManagerException e) {
            throw exception(e.getMessage());
        }
    }

    //获取订单详情
    public OrderDTO getOrderInfoBySerial(String orderSerial) {
        OrderDO orderDO = getOne(lambdaQuery().eq(OrderDO::getOrderSerial, orderSerial));

        return new OrderDTO(orderDO);
    }
}
